public class code2 {
    public int maxSubarraySumCircular(int[] nums) {
        int n = nums.length;

        int[] f = new int[n+1];//结果在中间：求以i位置为结果的所有子数组的最大值
        int[] g = new int[n+1];//结果在两边：求以i位置为结果的所有子数组的最小值

        int fmax = Integer.MIN_VALUE;
        int gmin = Integer.MAX_VALUE;
        int sum = 0;
        for(int i=1;i<n+1;i++) {
            int x = nums[i-1];
            sum += x;
            f[i] = Math.max(x,f[i-1]+x);
            fmax = Math.max(fmax,f[i]);
            g[i] = Math.min(x,g[i-1]+x);
            gmin = Math.min(gmin,g[i]);
        }

        return sum==gmin?fmax:Math.max(fmax,sum-gmin);

    }
}
